import 'package:flutter/material.dart';
import '../components/storage_box_card.dart';
import 'package:dio/dio.dart';

class StorageBox extends StatefulWidget {
  const StorageBox({super.key});

  @override
  State<StorageBox> createState() => _StorageBoxState();
}

class _StorageBoxState extends State<StorageBox> {
  late List<StorageData> _dataList = [];

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  Future<void> fetchData() async {
    try {
      final response = await Dio().get('https://mock.apipost.net/mock/2a39fbefcc64000/api/storageBox?apipost_id=2409d4463c3008');
      if (response.statusCode == 200) {
        // print("${response.data}");
        final jsonDataList = response.data['data'];
        // print("${response.data['data']}");
        setState(() {
          _dataList = jsonDataList.map<StorageData>((jsonData) {
            return StorageData(
              avatarUrl: jsonData['avatarUrl'],
              userName: jsonData['userName'],
              ip: jsonData['ip'],
              publishTime: jsonData['publishTime'],
              imagesUrl: List<String>.from(jsonData['imagesUrl']),
              title: jsonData['title'],
              totalNum: jsonData['totalNum'],
              nowNum: jsonData['nowNum'],
              deadline: jsonData['deadline'],
              position: jsonData['position'],
              loveNum: jsonData['loveNum'],
              shareNum: jsonData['shareNum'],
            );
          }).toList();
        });
        // print("_dataList: $_dataList");
      } else {
        throw Exception('加载数据失败');
      }
    } catch (e) {
      print('获取数据错误: $e');
      // 处理错误
    }
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: ListView(
        padding: const EdgeInsets.only(left: 20, right: 20),
        children: _dataList.map((data) => StorageBoxCard(data: data)).toList(),
      ),
    );
  }
}
